package org.csu.jpetstore_manage_system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.csu.jpetstore_manage_system.domain.Account;
import org.csu.jpetstore_manage_system.domain.Product;
import org.csu.jpetstore_manage_system.domain.SignOn;
import org.csu.jpetstore_manage_system.persistence.AccountMapper;
import org.csu.jpetstore_manage_system.persistence.SignOnMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.List;

@Service("accountService")
@MapperScan("org.csu.jpetstore_manage_system")
public class AccountService {

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private SignOnMapper signOnMapper;

    public List<Account> getAllAccount(){
        List<Account> accountList= accountMapper.selectList( new UpdateWrapper<>());
        return accountList;
    }

    public void updateAccount(Account account){
        accountMapper.updateById(account);
        SignOn signOn = new SignOn();
        signOn.setUsername(account.getUsername());
        signOn.setPassword(account.getPassword());
        signOnMapper.updateById(signOn);
    }

    public Account getAccountByUsername(String username){
       return accountMapper.selectById(username);
    }

    //新增账户
    public boolean insertAccount(Account account) {
        int count = accountMapper.insert(account);
        return count != 0;
    }

    //通过用户的ID删除某个账户
    public boolean deleteAccountById(String username) {
        int count = accountMapper.deleteById(username);
        return count != 0;
    }

    //通过用户名和密码取得account
    public Account getAccount(String username, String password){
        SignOn signOn = signOnMapper.selectOne(new UpdateWrapper<SignOn>().eq("username", username).eq("password", password));
        if(signOn != null){
            Account account = accountMapper.selectById(username);
            return account;
        }else return null;
    }


    //重置用户密码
    //@param account 待重置密码的用户
    //@param newPassword 新密码
    public boolean resetPassword(Account account, String newPassword){
        String username = account.getUsername();

        UpdateWrapper<SignOn> signOnUpdateWrapper = new UpdateWrapper<>();
        signOnUpdateWrapper.eq("username", username).set("password", newPassword);
        int count = signOnMapper.update(null, signOnUpdateWrapper);
        return count != 0;
    }
}
